package com.lfp.socketio;

import com.corundumstudio.socketio.SocketIOClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mos
 */
@Slf4j
@Component
public class SocketIoHolder {

    public static final String USER_KEY = "userId";

    public static final String NOTICE_KEY = "notice";

    /**
     * 存储已连接的客户端
     */
    private Map<String, SocketIOClient> clients = new ConcurrentHashMap<>();

    /**
     * 添加连接客户端
     * @param client
     */
    public void add(SocketIOClient client){
        String key = getParamByClient(client, USER_KEY);
        if( contains(key) ) {
            clients.remove(key);
        }
        clients.put(key, client);
        client.set(USER_KEY, key);
    }

    public SocketIOClient get(String key){
        if(clients.containsKey(key)){
            return clients.get(key);
        }
        return null;
    }

    public void remove(SocketIOClient client){
        String key = getParamByClient(client, USER_KEY);
        clients.remove(key);
    }

    public boolean contains(String key){
        if(clients.containsKey(key)){
            return true;
        }
        return false;
    }

    @Async
    public void notice(String key, Object data){
        SocketIOClient client = get(key);
        if(client != null){
            client.sendEvent(NOTICE_KEY, data);
        }
    }

    public Map<String, SocketIOClient> getClients() {
        return clients;
    }

    /**
     * 获取客户端连接参数
     * @param client
     * @param paramName
     * @return
     */
    public String getParamByClient(SocketIOClient client, String paramName){
        String singleUrlParam = client.getHandshakeData().getSingleUrlParam(paramName);
        log.error("---------------------------"+paramName+":"+singleUrlParam);
        return singleUrlParam == null ? "" : singleUrlParam;
    }
}
